import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { InputNumber, Input } from 'antd';
import 'moment/locale/zh-cn';
import { ModalC, TableC } from '../../../../../comps';
import '../../index.less';
import colors from '../../../../../css/colors';
import uuid from 'es6-uuid';

@connect(({ portfolioOptimizationM, loading }) => ({
  portfolioOptimizationM,
  loading,
}))
@Form.create()
export default class GroupC extends PureComponent {
  state = {
    dataSource: [], //表格数据
    errorMsg: '', //错误提示消息
    initColumns: [
      {
        //默认表头
        key: 'group',
        title: '组名',
      },
      {
        key: 'weightBottom',
        title: '权重下界(%)',
      },
      {
        key: 'weightTop',
        title: '权重上界(%)',
      },
    ],
  };

  componentDidMount() {
    this.props.onRef(this);
  }
  componentWillUnmount() {
    // 离开前清除models数据
  }

  //新增一行
  addRow = () => {
    const { dataSource } = this.state;
    dataSource.push({ order: dataSource.length + 1, id: uuid(4) });
    this.setState({
      dataSource: [...dataSource],
    });
  };
  //删除一行
  delRow = (row) => {
    const { dataSource } = this.state;
    const arr = dataSource.filter((item) => {
      return item.order != row.order;
    });
    arr.map((item, index) => {
      //删除之后 重置序号
      item.order = index + 1;
    });
    this.setState({
      dataSource: [...arr],
    });
  };
  isRepeat = (arr) => {
    //判断数组里是否有相同的元素
    var hash = {};
    for (var i in arr) {
      if (hash[arr[i]]) {
        return true;
      }
      hash[arr[i]] = true;
    }
    return false;
  };
  //校验每行数据
  checkObj = (arr, obj) => {
    for (var i = 0; i < arr.length; i++) {
      let key = arr[i];
      if (obj[key] !== 0 && !obj[key]) {
        this.setState({
          errorMsg: '请设置完整的条件!',
        });
        return key;
      }
    }
    return null;
  };

  checkData = () => {
    const { dataSource, errorMsg } = this.state;
    const { initColumns } = this.state;
    var msg = '';
    if (!dataSource.length) {
      msg = '请点击加号图标进行新增数据!';
      this.setState({
        errorMsg: msg,
      });
      return;
    }
    const columnKeys = initColumns.map((item) => item.key);
    for (var i = 0; i < dataSource.length; i++) {
      var item = dataSource[i];
      item.isRed = false;
      if (item.order != '总计') {
        var index = this.checkObj(columnKeys, item);
        if (index) {
          item.isRed = true;
          this.setState({
            dataSource: [...dataSource],
          });
          return null;
        }
        if (item.weightBottom && item.weightTop) {
          if (item.weightBottom > item.weightTop || item.weightBottom == item.weightTop) {
            msg = '权重上界必须大于权重下界';
            this.setState({
              errorMsg: msg,
            });
            item.isRed = true;
            this.setState({
              dataSource: [...dataSource],
            });
            return null;
          }
        }
      }
    }
    this.setState({
      errorMsg: '',
    });
    //判断是否有重复的组名
    if (this.isRepeat(dataSource.filter((item) => item.group).map((item) => item.group))) {
      msg = '组别名称不能重复';
      this.setState({
        errorMsg: msg,
      });
      return null;
    }
    return dataSource;
  };
  //表格提交
  submit = () => {
    var flag = this.checkData();
    if (flag) {
      this.props.getGroupData(flag);
      //关闭弹窗
      this.props.triggleVisible(false);
    }
  };
  //重置当前组件
  reset = () => {
    this.setState({
      dataSource: [], //表格数据
      errorMsg: '', //错误提示消息
    });
  };
  //初始化表格
  initTable = () => {
    const { initColumns } = this.state;
    const { dataSource, errorMsg } = this.state;
    let columns = initColumns.map((item) => {
      return item;
    }); //过滤需要展示的列
    const dom = document.querySelector('.groupModal .ant-modal-body');
    const currentHeight = dom ? dom.offsetHeight - 115 : '100%';
    columns.map((item) => {
      if (item.key != 'order' || item.key != 'operate') {
        item.width = parseFloat(80 / columns.length) + '%'; //设置宽度
        if (item.key == 'group') {
          item.render = (text, record) => {
            //设置展示的form表单
            return (
              <div className='current_input'>
                <Input
                  className={errorMsg && record.isRed ? 'has-error' : ''}
                  value={record[item.key]}
                  onChange={(e) => {
                    var pattern = /[`~!#$%^&*()_\+=<>?:"{}|~！#￥%……&*（）={}|《》？：“”【】、；‘’，。、\s+]/g;
                    if (pattern.test(e.target.value)) return; //不准输入特殊字符
                    record[item.key] = e.target.value ? e.target.value : undefined;
                    dataSource.map((row) => {
                      if (row.order == record.order) {
                        if (!record[item.key]) delete record[item.key];
                        row = { ...record };
                      }
                    });
                    this.setState({
                      //渲染表格,使修改生效
                      dataSource: [...dataSource],
                    });
                  }}
                />
              </div>
            );
          };
        } else {
          item.render = (text, record) => {
            //设置展示的form表单
            return (
              <InputNumber
                value={record[item.key]}
                className={errorMsg && record.isRed ? 'has-error' : ''}
                min={0}
                max={100}
                step={0.1}
                precision={2}
                placeholder={'请输入0-100的数字'}
                style={{ width: '100%' }}
                onChange={(value) => {
                  var pattern = /^(\+)?\d+(\.\d+)?$/;
                  if (!pattern.test(value)) return; //只允许>0 数字和小数时调用
                  if (value > 100) return;
                  record[item.key] = value;
                  dataSource.map((row) => {
                    if (row.order == record.order) {
                      row = { ...record };
                    }
                  });
                  this.setState({
                    //渲染表格,使修改生效
                    dataSource: [...dataSource],
                  });
                }}
              />
            );
          };
        }
      }
    });
    if (columns && columns.length && columns[columns.length - 1].key != 'operate') {
      columns.unshift({
        key: 'order',
        title: '序号',
        width: 100,
        align: 'center',
        render: (text) => {
          return text < 10 ? `0${text}` : text;
        },
      });
      columns.push({
        key: 'operate',
        title: '操作',
        align: 'left',
        render: (text, record) => {
          return (
            <MinusCircleOutlined
              style={{ color: colors.debtAndProfit.text[0], fontSize: '16px' }}
              onClick={() => {
                this.delRow(record);
              }}
            />
          );
        },
      });
    }
    return <TableC columns={columns} dataSource={dataSource} rowKey='order' hidePage={true} scroll={{ x: '100%', y: currentHeight }} />;
  };
  render() {
    const { errorMsg } = this.state;
    const modalProps = {
      visible: this.props.visible,
      onOk: () => {
        this.submit();
      },
      onCancel: () => {
        this.setState({
          dataSource: JSON.parse(JSON.stringify(this.props.oldData)),
          errorMsg: '',
        });
        //关闭弹窗
        this.props.triggleVisible(false);
      },
      title: '分组约束',
      className: 'groupModal',
      height: 440, //内容区域的高度
      width: 960,
    };
    return (
      <ModalC {...modalProps}>
        {this.initTable()}
        <div className='addRow'>
          <PlusCircleOutlined onClick={this.addRow} />
          <span style={{ display: errorMsg ? 'inherit' : 'none', color: colors.debtAndProfit.text[0] }}>{errorMsg}</span>
        </div>
      </ModalC>
    );
  }
}
